package com.isoft.controller;

import com.isoft.entity.DfmePokeEntity;
import com.isoft.service.DfmePokeService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/flight/poke")
public class DfmePokeController {
    private static final Logger logger = LoggerFactory.getLogger(DfmePokeController.class);

    // 有效的STATUS值列表
    private static final List<String> VALID_STATUS = Arrays.asList(
            "NORMAL", "DELAYED", "CANCELLED", "BOARDING",
            "DEPARTED", "ALTERNATE", "RETURNED", "BOARDING_COMPLETED"
    );

    // 状态映射表
    private static final Map<String, String> STATUS_MAPPING = new HashMap<>();
    static {
        STATUS_MAPPING.put("POK", "NORMAL");  // 将POK映射为NORMAL
        STATUS_MAPPING.put("正常", "NORMAL");
        STATUS_MAPPING.put("延误", "DELAYED");
        STATUS_MAPPING.put("取消", "CANCELLED");
        STATUS_MAPPING.put("登机", "BOARDING");
        STATUS_MAPPING.put("起飞", "DEPARTED");
        // 可以根据需要添加更多映射
    }

    @Autowired
    private DfmePokeService dfmePokeService;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @PostMapping(value = "/upload",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> uploadFlightPokeData(@RequestParam("file") MultipartFile file) {
        try {
            logger.info("Received DFME-POKE file upload request: {}", file.getOriginalFilename());

            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("{\"error\":\"File cannot be empty\"}");
            }

            if (!file.getOriginalFilename().toLowerCase().endsWith(".xml")) {
                return ResponseEntity.badRequest().body("{\"error\":\"Only XML files are supported\"}");
            }

            // 解析XML文件
            String xmlContent = new String(file.getBytes());
            DfmePokeEntity entity = xmlParserUtil.parseXml(xmlContent, DfmePokeEntity.class);

            // 验证并映射STATUS值
            if (entity.getDflt() != null && entity.getDflt().getStatus() != null) {
                String status = entity.getDflt().getStatus();
                if (!VALID_STATUS.contains(status)) {
                    // 检查是否有映射
                    if (STATUS_MAPPING.containsKey(status)) {
                        String mappedStatus = STATUS_MAPPING.get(status);
                        logger.info("Mapping STATUS value: {} -> {}", status, mappedStatus);
                        entity.getDflt().setStatus(mappedStatus);
                    } else {
                        return ResponseEntity.badRequest().body(
                                "{\"error\":\"Invalid STATUS value: " + status +
                                        "\",\"validValues\":" + Arrays.toString(VALID_STATUS.toArray()) + "}");
                    }
                }
            }

            // 处理数据
            dfmePokeService.parseAndSave(entity);

            return ResponseEntity.ok("{\"message\":\"DFME-POKE data processed successfully\"}");
        } catch (Exception e) {
            logger.error("DFME-POKE file upload failed", e);
            return ResponseEntity.internalServerError()
                    .body("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }

    @GetMapping(value = "/{flightId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> getFlightPokeData(@PathVariable Long flightId) {
        try {
            logger.info("Getting DFME-POKE data for flight ID: {}", flightId);

            // 这里应该实现查询逻辑，返回特定航班的POKE数据
            // 简化示例，实际应根据业务需求实现
            return ResponseEntity.ok("{\"message\":\"DFME-POKE data for flight ID: " + flightId + "\"}");
        } catch (Exception e) {
            logger.error("Failed to get DFME-POKE data", e);
            return ResponseEntity.internalServerError()
                    .body("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }
}